package zhao.ben.quan.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import zhao.ben.quan.dao.OrderSettingDao;
import zhao.ben.quan.pojo.OrderSetting;
import zhao.ben.quan.service.OrderSettingService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预约设置服务
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    //注入持久层
    @Autowired
    private OrderSettingDao orderSettingDao;

    //批量导入预约设置数据
    public void add(List<OrderSetting> data) {
        //对集合判空
        if (data != null && data.size() > 0) {
            for (OrderSetting orderSetting : data) {
                //判断当前日期是否进行了预约设置
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

                if(countByOrderDate>0){
                    //已经进行预约设置,执行更新操作
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else {
                    //没有进行预约设置,执行插入操作
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }


    //查询年月展示数据--每页显示的数据
    public List<Map> getOrderSettingByMonth(String data) {
        //丛数据库查询日期段
        String begin = data + "-1";//2020-6-1;
        String end = data + "-31";//2020-6-31;  没有31,有多少显示多少

        //创建map集合,存储查询范围
        Map<String,String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);

        //掉用DAO,根据日期范围查询预约的设置数据
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);

        //创建list<map>,封装对象,用于返回数据
        List<Map> result = new ArrayList<>();

        if (list!=null &&list.size()>0){
            //遍历后台查询数据,用于对象封装
            for (OrderSetting orderSetting : list) {
                Map<String,Object> m = new HashMap<>();
                m.put("date",orderSetting.getOrderDate().getDate());//获取日期数字(几号)
                m.put("number",orderSetting.getNumber());//获取可预约人数
                m.put("reservations",orderSetting.getReservations());//获取已预约人数
                result.add(m);//把map添加到list集合
            }
        }
        return result;
    }


    //预约设置
    public void editNumberByDate(OrderSetting orderSetting) {

        //判断当前日期是否进行了预约设置
        long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

        if(countByOrderDate>0){
            //已经进行预约设置,执行更新操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
            return;
        }
            //没有进行预约设置,执行插入操作
            orderSettingDao.add(orderSetting);
    }
}
